package com.moorecat.app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.moorecat.MooerApplication;
import com.moorecat.R;
import com.moorecat.bean.SearchLocation;
import com.moorecat.bean.Shop;
import com.moorecat.http.HttpUtils;
import com.moorecat.utils.ui.ProgressLinearLayout;
import com.moorecat.utils.ui.UiUtils;

public class SignBusiness extends Activity implements OnClickListener,
		OnScrollListener {

	private static final String TAG = "SignBusiness";

	private EditText edit;

	private ImageView searchButton;

	private ListView listView;

	private SignBusinessAdapter adapter;

	private ProgressLinearLayout footer;

	private List<Shop> list = new ArrayList<Shop>();

	private MooerApplication mooerApp;

	private SearchLocation location;

	private long taskId;

	private AsyncTask bitmapTask;

	private int limit = 20, limitStart = 0;

	private boolean loadOver, loading, isCancelled;

	private String search;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sign_business);
		mooerApp = (MooerApplication) getApplication();
		edit = (EditText) findViewById(R.id.search);
		searchButton = (ImageView) findViewById(R.id.search_btn);
		listView = (ListView) findViewById(R.id.listview);
		listView = (ListView) findViewById(R.id.listview);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
		adapter = new SignBusinessAdapter();
		listView.setAdapter(adapter);
		listView.setOnScrollListener(this);

		searchButton.setOnClickListener(this);
		footer.setOnClickListener(this);
		edit.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView paramTextView, int paramInt,
					KeyEvent paramKeyEvent) {
				if (edit.getText().toString().length() > 0) {
					search = edit.getText().toString();
					if (search == null || "".equals(search.trim())) {
						search = "";
					}
					location.setSearch(search);
					limitStart = 0;
					list.clear();
					adapter.notifyDataSetChanged();
					footer.initView();
					listView.addFooterView(footer);
					new SignBusinessTask().execute(location);
					InputMethodManager imm = (InputMethodManager) SignBusiness.this
							.getSystemService(Context.INPUT_METHOD_SERVICE);

					if (imm.isActive()) {

						imm.hideSoftInputFromWindow(
								edit.getApplicationWindowToken(), 0);
					}
				} else {
					UiUtils.showToast(SignBusiness.this, "请输入您要查询的关键字");
				}
				return false;
			}
		});

		location = new SearchLocation();
		// location.setLatitude(32.05724);
		// location.setLongitude(118.740275);
		location.setLatitude(mooerApp.getLatitude());
		location.setLongitude(mooerApp.getLongitude());
		location.setOrderBy("concern_num");
		location.setRadius(2000);
		new SignBusinessTask().execute(location);
	}

	public class SignBusinessAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			View itemView = (LinearLayout) LayoutInflater.from(
					SignBusiness.this).inflate(R.layout.sign_business_item,
					null);
			ImageView pic = (ImageView) itemView.findViewById(R.id.icon);
			TextView name = (TextView) itemView
					.findViewById(R.id.business_name);
			TextView address = (TextView) itemView
					.findViewById(R.id.business_address);
			TextView meters = (TextView) itemView
					.findViewById(R.id.business_meters);
			name.setText(list.get(position).getName());
			address.setText(list.get(position).getAddress().getAddress1());
			meters.setText(list.get(position).getDistance() + "米");
			pic.setImageBitmap(list.get(position).getIcon());
			itemView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Shop shop = list.get(position).copy();
					Intent intent = new Intent(SignBusiness.this,
							Business.class);
					intent.putExtra("businessInfo", shop);
					intent.putExtra("tab", "sign");
					startActivity(intent);
				}
			});
			return itemView;
		}

	}

	@Override
	public void onClick(View v) {
		if (v == searchButton) {
			if (edit.getText().toString().length() > 0) {
				search = edit.getText().toString();
				if (search == null || "".equals(search.trim())) {
					search = "";
				}
				location.setSearch(search);
				limitStart = 0;
				list.clear();
				adapter.notifyDataSetChanged();
				footer.initView();
				listView.addFooterView(footer);
				new SignBusinessTask().execute(location);
			} else {
				UiUtils.showToast(this, "请输入您要查询的关键字");
			}
		} else if (v == footer.reload) {
			footer.setVisibility(View.VISIBLE, View.VISIBLE, View.GONE,
					View.GONE);
			new SignBusinessTask().execute(location);
		}

	}

	public class SignBusinessTask extends
			AsyncTask<SearchLocation, Integer, List<Shop>> {

		private boolean isException;

		@Override
		protected List<Shop> doInBackground(SearchLocation... location) {
			loading = true;
			List<Shop> list = null;
			try {
                location[0].setOrderBy("distance");
				list = HttpUtils.fetchNearShopList(location[0], limitStart,
						limit);
				for (Shop shop : list) {
					shop.setIcon(mooerApp.getShopListDefaultIcon());
				}
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<Shop> result) {
			super.onPostExecute(result);
			loading = false;
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					if (result.size() < limit) {
						listView.removeFooterView(footer);
					}
					list.addAll(result);
					adapter.notifyDataSetChanged();
					bitmapTask = new BitmapTask().execute("");
				} else {
					if (limitStart == 0) {
						footer.setVisibility(View.GONE, View.GONE,
								View.VISIBLE, View.GONE);
						footer.setText(null, "暂无可签到商家");
					} else {
						loadOver = true;
						listView.removeFooterView(footer);
						Log.i(TAG, "ListView load over");

					}
				}
			}
		}

	}

	private class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<Shop> cacheList = new ArrayList<Shop>();
			cacheList.addAll(list);
			Iterator<Shop> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程
				 */
				if (id != taskId || isCancelled) {
					break;
				}
				Shop shop = it.next();
				Bitmap icon = null;
				try {
					if (shop.getIcon() == mooerApp.getShopListDefaultIcon()) {
						if (shop.getLogo() != null
								&& !"".equals(shop.getLogo())) {
							icon = HttpUtils.downloadBitmap(shop.getLogo());
							if (icon != null) {
								shop.setIcon(icon);
								publishProgress(0);
							}
						}
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			adapter.notifyDataSetChanged();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bitmapTask != null) {
			boolean isSuccess = bitmapTask.cancel(true);
			Log.i(TAG, "signBusinessTask cancelled " + isSuccess);
			isCancelled = true;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (list.size() == 0) {
			return;
		}
		if (view.getLastVisiblePosition() == view.getCount() - 1) {
			if (view.getCount() < limitStart || loadOver || loading) {
				Log.d(TAG, view.getCount() + "|" + limitStart + "| load over");
				return;
			}
			limitStart = limitStart + limit;
			limit = 5;
			new SignBusinessTask().execute(location);
		}
		if (loadOver) {
			listView.removeFooterView(footer);
		}

	}

}
